function replaceNonCoprimes(nums) {
  // 计算最大公约数
  function gcd(a, b) {
    while (b !== 0) {
      [a, b] = [b, a % b];
    }
    return a;
  }

  // 计算最小公倍数
  function lcm(a, b) {
    return (a / gcd(a, b)) * b;
  }

  const stack = [];

  for (const num of nums) {
    let current = num;
    // 检查栈顶元素与当前元素是否为非互质数，如果是则合并
    while (stack.length > 0) {
      const top = stack[stack.length - 1];
      const g = gcd(top, current);

      if (g > 1) {
        // 合并两个数，替换为它们的最小公倍数
        current = lcm(top, current);
        stack.pop();
      } else {
        // 互质，不能合并，退出循环
        break;
      }
    }
    stack.push(current);
  }

  return stack;
}

// 测试示例
console.log(replaceNonCoprimes([6, 4, 3, 2, 7, 6, 2])); // 输出: [12,7,6]
console.log(replaceNonCoprimes([2, 2, 1, 1, 3, 3, 3])); // 输出: [2,1,1,3]
